package echo.demo2;

import echo.future.ReceiveInvoker;
import echo.protocol.MessageProtocol;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.ExecutorService;

public class ClientHandler extends ChannelInboundHandlerAdapter {
    private ExecutorService executorService;

    public ClientHandler(ExecutorService executorService) {
        this.executorService = executorService;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        MessageProtocol messageProtocol = (MessageProtocol) msg;
        executorService.submit(new ReceiveInvoker(messageProtocol));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//        ?
        ctx.close();
    }

    public static void main(String[] args) {

        ByteBuf buffer = Unpooled.buffer();

        buffer.writeInt(Integer.MAX_VALUE);
        for (int i = 0; i < 1000; i++) {
            buffer.writeInt(i);
        }
        buffer.writeBytes(new byte[]{97, 115, 100, 102, 105, 100});
        for (int i = 0; i < 100; i++) {
            int i1 = buffer.readInt();
            System.out.println(i1 + "  wIdx:" + buffer.writerIndex()+" ridx:"+buffer.readerIndex() + " cap:"+buffer.capacity());

        }
        System.out.println(buffer);
    }

}
